<?php

namespace App\Models\Train\TrainOrderRefund\Refunds;

use App\Models\Task\SnapTasks\SnapTask;
use App\Models\Train\TrainOrders\TrainOrder;
use App\Models\Trip\SnapTaskUpgradePay\SnapTaskUpgradePay;
use App\Models\Trip\TripOrderCosts\Repositories\Interfaces\TripOrderCostsRepositoryInterface;
use App\Models\Trip\TripOrderCosts\TripOrderCost;
use App\Models\Trip\TripOrderRefund\RefundDetail;
use App\Models\Trip\TripOrderRefund\Refunds\dealRefundInterface;
use App\Models\Trip\TripOrderRefund\TripOrderRefund;
use Exception;
use Illuminate\Support\Facades\Log;
use JetBrains\PhpStorm\ArrayShape;

class dealAloneUpgradeTaskRefund implements dealRefundInterface
{
    // 处理单独支付的 升级包退款数据
    private SnapTask        $task;
    private TrainOrder      $order_info;
    private TripOrderRefund $refund_model;
    private string          $log_key;
    private array           $refundInfos;
    private array           $refund_datas;
    private bool            $has_alone_pay_record;

    public function __construct(SnapTask $task, TrainOrder $order_info)
    {
        $this->task                 = $task;
        $this->order_info           = $order_info;
        $this->refund_model         = new TripOrderRefund();
        $this->log_key              = "单独支付的升级包退款:task_id-{$task->getTaskId()},order_sn-{$order_info->getOrderSn()}";
        $this->refundInfos          = [];
        $this->refund_datas         = [];
        $this->has_alone_pay_record = false;
        $this->dealRefundData();
    }


    private function dealRefundData(): void
    {
        $upgrade_pay      = new SnapTaskUpgradePay();
        $upgrade_pay_info = $upgrade_pay->findOneByTask($this->task);
        $costRepo         = app(TripOrderCostsRepositoryInterface::class);
        if (!$upgrade_pay_info) {
            Log::info("{$this->log_key},无相关支付信息,非单独支付");
            return;
        }
        $this->has_alone_pay_record = true;
        $pay_success                = false;
        if ($upgrade_pay_info->isPaySuccess()) {
            $pay_success = true;
        } else {
            // 通过支付反向查询
            try {
                $pay_info    = $upgrade_pay_info->order_pay;
                $pay_success = $pay_info->isPayResultDataSuccess();
            } catch (Exception $exception) {
                Log::error("{$this->log_key},任务取消,退款验证曾发起的支付结果,{$exception->getMessage()}");
            }
            Log::info("{$this->log_key},反查支付 pay_sn:{$upgrade_pay_info->getPaySn()},当前状态为已支付");
        }

        // 当存在单独的加速包升级支付时
        if ($pay_success) {
            // 验证是否退过
            $upgrade_refund_sn   = "R".$upgrade_pay_info->getPaySn();
            $upgrade_refund_info = $this->refund_model->whereOutRefundNo($upgrade_refund_sn)->first();
            if ($upgrade_refund_info) {
                Log::info("{$this->log_key}:升级支付已有退款记录,refund_sn:{$upgrade_refund_sn}");
                // 如果未退款成功 则加入退款数组中
                if (!$upgrade_refund_info->isRefundedSuccess()) {
                    $this->refundInfos[] = $upgrade_refund_info;
                }
            } else {
                $refund_details_upgrade = [];
                $cost_type              = TripOrderCost::COST_TYPE_SNAP_HIGH_LEVEL_SERVICE_FEE;
                $cost_name              = TripOrderCost::COST_TYPE_DESC[TripOrderCost::COST_TYPE_SNAP_HIGH_LEVEL_SERVICE_FEE];
                $upgrade_pay_cost       = $costRepo->findOneByOrderAndTypeName($this->order_info, $cost_type, $cost_name);
                if ($upgrade_pay_cost) {
                    $refund_data              = [
                        "user_id"         => $this->order_info->getUserId(),
                        "refund_sn"       => $upgrade_refund_sn,
                        "out_refund_no"   => $upgrade_refund_sn,
                        "out_trade_no"    => $upgrade_pay_info->getPaySn(),
                        "origin_order_sn" => $this->order_info->getOriginOrderSn(),
                        "order_sn"        => $this->order_info->getOrderSn(),
                        "ticket_price"    => 0,
                        "refund_amount"   => $upgrade_pay_info->getPayAmount(),
                        "pay_amount"      => $upgrade_pay_info->getPayAmount(),
                        "has_ticket"      => $this->refund_model::REFUND_NO_TICKET,
                        "refund_state"    => $this->refund_model::REFUND_STATE_REFUNDING, //  需要立即退款
                        "title"           => "无票退款-高速抢票",
                        "refund_type"     => $this->refund_model::REFUND_TYPE_NO_TICKET,
                        "trip_type"       => $this->order_info->getTripType(),
                    ];
                    $refund_details_upgrade[] = [
                        "user_id"      => $this->order_info->getUserId(),
                        "refund_sn"    => $upgrade_refund_sn,
                        "order_sn"     => $this->order_info->getOrderSn(),
                        "out_trade_no" => $upgrade_pay_info->getPaySn(),
                        "type"         => RefundDetail::TASK_UPGRADE_LEVEL_FEE_REFUND,
                        "name"         => RefundDetail::getTypeDesc(RefundDetail::TASK_UPGRADE_LEVEL_FEE_REFUND),
                        "amount"       => $upgrade_pay_cost->getPrice(),
                        "count"        => $upgrade_pay_cost->getCount(),
                        "trip_type"    => $this->order_info->getTripType(),
                    ];
                    $refund_data['details']   = $refund_details_upgrade;
                    $this->refund_datas[]     = $refund_data;
                }
            }
        }
    }

    #[ArrayShape([
        TripOrderRefund::class,
    ])] public function getNeedRefundInfos(): array
    {
        return $this->refundInfos;
    }

    public function getNewRefundData(): array
    {
        return $this->refund_datas;
    }

    public function hasAlonePayRecord(): bool
    {
        return $this->has_alone_pay_record;
    }
}